package com.feather.tenia.mysql.fetcher;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.feather.common.data.Column;
import com.feather.common.data.DataColumn;
import com.feather.common.data.DataItem;
import com.feather.common.data.simple.SimpleColumnCollection;
import com.feather.common.data.simple.SimpleDataRow;
import com.feather.common.data.simple.SimpleDataRowCollection;
import com.feather.common.data.simple.SimpleDataTable;
import com.feather.common.db.DbFetcher;
import com.feather.common.db.TypeMapping;
import com.feather.tenia.Tenia;
import com.feather.tenia.adapter.data.MetaData;
import com.feather.tenia.adapter.fetcher.NormalFetcher;

/**
 * @author flogyin
 */
public class CURSOR_Fetcher implements DbFetcher {
	private Tenia	tenia;

	public CURSOR_Fetcher(Tenia tenia) {
		this.tenia = tenia;
	}

	@Override
	public String getDbType() {
		return "cursor";
	}

	@Override
	public int getSqlType() {
		return 715;
	}

	/**
	 * mysql特点： 查询 或 存储（直接返回select的记录集），因此都是解析 ResultSet.
	 */
	@Override
	public DataItem fetch(ResultSet rs, Column column) throws SQLException {
		ResultSetMetaData rsmd = rs.getMetaData();

		SimpleColumnCollection columnCollection = new SimpleColumnCollection();
		MetaData metaData = MetaData.load(rsmd, columnCollection, this.tenia != null ? this.tenia.getMetaDataColumnHandler() : null);

		SimpleDataRowCollection dataRowCollection = new SimpleDataRowCollection();
		try {
			TypeMapping typeMapping = this.tenia != null ? this.tenia.getTypeMapping() : null;
			while (rs.next()) {
				SimpleDataRow dataRow = new SimpleDataRow();
				for (int i = 0; i < metaData.count; i++) {
					Column current = columnCollection.get(i);
					DbFetcher fetcher = typeMapping != null ? typeMapping.lookup(current.getDataTypeName()) : null;
					if (fetcher == null) {
						fetcher = NormalFetcher.INSTANCE;
					}
					DataColumn dataColumn = (DataColumn) fetcher.fetch(rs, current);
					dataRow.add(dataColumn);
				}
				dataRowCollection.add(dataRow);
			}
		} finally {
			try {
				rs.close();
			} catch (Exception ex) {
			}
		}

		SimpleDataTable dataTable = new SimpleDataTable(columnCollection, dataRowCollection);
		if (column != null) {
			dataTable.setCatalog(column.getCatalog());
			dataTable.setName(column.getName());
		} else {
			dataTable.setCatalog(metaData.catalog);
			dataTable.setName(metaData.table);
		}
		return dataTable;
	}

	/**
	 * mysql特点： 存储的 CallableStatement 不会有要解析的记录集.
	 */
	@Override
	public DataItem fetch(CallableStatement statement, Column column) throws SQLException {
		return null;
	}
}
